<template>
  <div>
    <side-title>基本设置</side-title>
    <div class="mt-2 px-8 py-4 text-sm" style="width: 800px">
      <el-form label-position="left" size="small" ref="editBasicFormComponent" :model="editBasicForm"
        label-width="80px">
        <el-form-item label="接口名称">
          <el-input v-model="editBasicForm.summary"></el-input>
        </el-form-item>

        <el-form-item label="接口路径">
          <div class="flex">
            <el-select v-model="editBasicForm.method">
              <el-option v-for="item in methodOptions" :key="item" :label="item" :value="item"></el-option>
            </el-select>
            <el-input v-model="editBasicForm.path"></el-input>
          </div>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="editBasicForm.statusId">
            <el-option v-for="item in apiStore.statusOptions" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <side-title>请求参数设置</side-title>
    <div class="text-center">
      <el-radio-group v-model="requestMethod">
        <el-radio-button v-for="item in requestContentTypeOptions" :key="item" :label="item">{{ item
          }}</el-radio-button>
      </el-radio-group>
    </div>

    <div v-show="requestMethod === 'Body'" class="mt-2 px-8 py-4 text-sm">
      <el-radio-group v-model="requestContentType">
        <el-radio label="form">form</el-radio>
        <el-radio label="json">json</el-radio>
      </el-radio-group>
      <div class="mt-8" v-show="requestContentType === 'form'">
        <form-edit ref="formEditComponent" />
      </div>
      <div class="mt-8" v-show="requestContentType === 'json'">
        <json-edit ref="jsonEditComponent" />
      </div>
    </div>
    <div v-show="requestMethod === 'Query'" class="mt-2 px-8 py-4 text-sm">
      <query-edit ref="queryEditComponent" />
    </div>

    <div v-show="requestMethod === 'Header'" class="mt-2 px-8 py-4 text-sm">
      <header-edit ref="headerEditComponent" />
    </div>

    <side-title>返回数据设置</side-title>
    <el-tabs class="mt-2 response-tab mb-16" v-model="responseTabValue" type="card" @edit="onTabsEdit" editable>
      <el-tab-pane :key="item.statusCode" v-for="item in responses" :label="item.statusCode" :name="item.statusCode">
        <div class="p-2">
          <div class="flex items-center mt-2">
            <span>HTTP状态码：</span>
            <el-input v-model="item._statusCode" @change="
              responseTabValue = item._statusCode;
            item.statusCode = item._statusCode;
            " size="small" style="width: 80px"></el-input>
            <span class="ms-3">名称：</span>
            <el-input v-model="item.description" size="small" style="width: 180px"></el-input>
            <span class="ms-3">内容格式：</span>
            <el-select size="small" v-model="item.responsesType">
              <el-option v-for="item in responsesTypeOptions" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </div>
          <div v-if="item.responsesType === 'application/json'">
            <json-edit ref="resJsonEditComponent" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- <div class="mt-2 px-8 py-4 text-sm" style="width: 800px">
      <el-form label-position="left" label-width="150px">
        <el-form-item label="响应类型">
          <el-select v-model="responseType">
            <el-option label="json" value="json"></el-option>
            <el-option label="blob" value="blob"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div> -->
    <!-- <div v-show="responseType === 'json'" class="px-8 py-4 text-sm">
      <div>
        <json-edit ref="resJsonEditComponent" />
      </div>
    </div> -->

    <div class="text-right sticky right-0 bottom-0" style="z-index: 9999">
      <v-btn @click="onUpdate" class="me-1 ms-auto" color="primary">
        <!-- <span v-if="!isNewProject">创建</span> -->
        <span>更新</span>
      </v-btn>
    </div>
  </div>
</template>

<script>
import {
  computed,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRef,
  watch,
} from "@vue/composition-api";
import { useApiStore } from "@/store/api";
import HeaderEdit from "@/components/HeaderEdit/index.vue";
import QueryEdit from "@/components/QueryEdit/index.vue";
import FormEdit from "@/components/FormEdit/index.vue";
import JsonEdit from "@/components/BodyEdit/index.vue";
import SideTitle from "@/components/SideTitle/index.vue";
export default {
  components: {
    QueryEdit,
    JsonEdit,
    FormEdit,
    HeaderEdit,
    SideTitle,
  },
  setup() {
    let uuid = 0;
    const apiStore = useApiStore();
    const queryEditComponent = ref(null);
    const formEditComponent = ref(null);
    const jsonEditComponent = ref(null);
    const headerEditComponent = ref(null);
    onMounted(() => {
      const val = apiStore.doc;
      editBasicForm.summary = val.summary;
      editBasicForm.method = val.method;
      editBasicForm.path = val.path;
      editBasicForm.statusId = val.statusId
      if (val.parameters) {
        queryEditComponent.value.setFormItems(val.parameters);
        headerEditComponent.value.setFormItems(val.parameters);
      }
      if (val.requestBody && val.requestBody.content) {
        if (val.requestBody.content["application/json"]) {
          const content = apiStore.doc.requestBody.content["application/json"];
          if (content && content.schema && content.schema.properties) {
            jsonEditComponent.value.setBody(content.schema.properties);
          }
        }
        if (val.requestBody.content["multipart/form-data"]) {
          formEditComponent.value.setFormItems(val.requestBody);
        }
      }
      if (val.responses) {
        responses.value = Object.entries(val.responses).map(([k, v]) => {
          if (v.content) {
            const key = Object.keys(v.content)[0];
            let responsesType = responsesTypeOptions.find(
              (item) => item.value === key
            );
            const tmpSchema = {
                "type": "object",
                "description": "",
                "properties": {

                }
              }
            let schema = null
            if (!responsesType) {
              responsesType = "application/json";
              schema = tmpSchema
            } else {
              responsesType = responsesType.value;
              schema = v.content[key] && v.content[key].schema
            }

            if (!schema) {
              schema = tmpSchema
            }
            

            return {
              _statusCode: k,
              statusCode: k,
              description: v.description,
              responsesType,
              schema
            };
          } else {
            return {
              _statusCode: k,
              statusCode: k,
              description: v.description,
            };
          }
        });
        nextTick(() => {
          const jsonEditList = [...resJsonEditComponent.value];
          responses.value.forEach((item) => {
            if (item.schema) {
              if (item.responsesType === "application/json") {
                const jsonEdit = jsonEditList.shift();
                if (item.schema && item.schema.properties) {
                  jsonEdit.setBody(item.schema.properties);
                }
              }
            }
          });
        });
      }
    });

    const methodOptions = ["GET", "POST", "PUT"];
    const editBasicForm = reactive({
      summary: "",
      method: "",
      path: "",
      statusId: 0,
    });
    const requestMethod = ref("Query");
    const requestContentTypeOptions = computed(() => {
      if (editBasicForm.method === "GET") {
        return ["Query", "Header"];
      } else {
        return ["Query", "Body", "Header"];
      }
    });
    const requestContentType = ref("form");

    const responseType = ref("json");

    // const isNewProject = computed(() => !!apiStore.docId)

    function onUpdate() {
      const updatedResponses = {};
      if (resJsonEditComponent.value) {
        const jsonEditList = [...resJsonEditComponent.value];
        responses.value.forEach((item) => {
          const content = {};
          const res = {
            description: item.description,
            content,
          };
          updatedResponses[item.statusCode] = res;
          if (item.responsesType === "application/json") {
              const jsonEdit = jsonEditList.shift();
              content[item.responsesType] = {};
              content[item.responsesType].schema = jsonEdit.getBody();
            }
        });
      }
      apiStore.updateApiDoc({
        parameters: [
          ...queryEditComponent.value.getFormItems(),
          ...headerEditComponent.value.getFormItems(),
        ],
        requestBody: {
          content: {
            "multipart/form-data": {
              schema: formEditComponent.value.getFormItems(),
            },
            "application/json": {
              schema: jsonEditComponent.value.getBody(),
            },
          },
        },
        responses: updatedResponses,
        ...editBasicForm,
      });
    }
    const responseTabValue = ref("200");
    const responses = ref([]);
    const responsesTypeOptions = reactive([
      {
        label: "JSON",
        value: "application/json",
      },
      {
        label: "BLOB",
        value: "application/octet-stream",
      },
    ]);
    const resJsonEditComponent = ref(null);

    function onTabsEdit(targetName, action) {
      if (action === "add") {
        responses.value.push({
          _statusCode: "状态码",
          statusCode: "状态码",
          responseType: "application/json",
        });
      } else if (action === "remove") {
        const index = responses.value.findIndex(
          (item) => item.statusCode === targetName
        );
        responses.value.splice(index, 1);
      }
    }

    return {
      apiStore,

      queryEditComponent,
      formEditComponent,
      jsonEditComponent,
      headerEditComponent,
      editBasicForm,
      methodOptions,
      requestMethod,
      requestContentTypeOptions,
      requestContentType,
      responseType,
      // isNewProject,
      onUpdate,

      responses,
      responseTabValue,
      responsesTypeOptions,
      resJsonEditComponent,

      onTabsEdit,
    };
  },
};
</script>

<style scoped>
.response-tab>>>.el-tabs__header {
  margin-bottom: 0px;
}

.response-tab>>>.el-tabs__content {
  border-left: 1px solid #e4e7ed;
  border-right: 1px solid #e4e7ed;
  border-bottom: 1px solid #e4e7ed;
}
</style>